<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use GuzzleHttp\Client;
use OpenTracing\GlobalTracer;

class HttpService
{
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function get(string $url, array $params = [], array $options = [])
    {
        $fullurl = $url . '?' . http_build_query($params);
        if (config('app.env') !== 'test') {
            return $this->client->get($fullurl, $options)->getBody()->getContents();
        }
        $tracer = GlobalTracer::get();
        $activeSpan = $tracer->getActiveSpan();
        $startTime = microtime(true);
        $content = $this->client->get($fullurl, $options)->getBody()->getContents();
        $endTime = microtime(true);
        $span = $tracer->startSpan('http.get', [
            'child_of' => $activeSpan->getContext(),
            'start_time' => (int)($startTime * 1000 * 1000),
        ]);
        $span->setTag('http.fullurl', $fullurl);
        $span->setTag('http.client_time', $endTime - $startTime);
        $span->finish();
        return $content;
    }

    public function post(string $url, array $params = [], array $options = [])
    {
        if (! empty($params)) {
            $options['json'] = $params;
        }
        if (config('app.env') !== 'test') {
            return $this->client->post($url, $options)->getBody()->getContents();
        }
        $tracer = GlobalTracer::get();
        $activeSpan = $tracer->getActiveSpan();
        $startTime = microtime(true);
        $content = $this->client->post($url, $options)->getBody()->getContents();
        $endTime = microtime(true);
        $span = $tracer->startSpan('http.post', [
            'child_of' => $activeSpan->getContext(),
            'start_time' => (int)($startTime * 1000 * 1000),
        ]);
        $span->setTag('http.url', $url);
        $span->setTag('http.client_time', $endTime - $startTime);
        $span->finish();
        return $content;
    }
}
